const PhoenixError = require('./../../models/phoenix-error');
const testCaseGroups = require('../../models/test-case-groups');
const projects = require('../../models/projects');
const projectVersions = require('../../models/project-versions');
const files = require('../../models/files');
const functions = require('../../models/functions');
/**
 * 判断URL参数中测试编组Id是否存在
 * @param req
 * @param res
 * @param next
 */

function requireTestCaseGroupExist(req, res, next) {
  (async () => {
    const { groupId } = req.params;
    if (!groupId) {
      next(new PhoenixError('invalid request', 'Missing parameters. "groupId" is required'));
    }
    const groups = await testCaseGroups.getGroupById(groupId);
    if (groups.length === 0) {
      return Promise.reject(new PhoenixError('not found', 'Not found, group not found'));
    }
    const group = groups[0];
    req.$group = group;
    const {
      projectId, versionId, fileId, functionId,
    } = group;
    const [project, projectVersion, file, func] = await Promise.all([
      projects.getProject(projectId),
      projectVersions.getVersion(versionId),
      files.getFile(fileId),
      functions.getFunction(functionId),
    ]);
    if (!projectVersion) {
      return Promise.reject(new PhoenixError('not found', 'Not found, projectVersion not found'));
    }
    if (!project) {
      return Promise.reject(new PhoenixError('not found', 'Not found, project not found'));
    }
    if (!file) {
      return Promise.reject(new PhoenixError('not found', 'Not found, file not found'));
    }
    if (!func) {
      return Promise.reject(new PhoenixError('not found', 'Not found, function not found'));
    }
    req.$project = project;
    req.$projectVersion = projectVersion;
    req.$file = file;
    req.$function = func;
    return Promise.resolve(next());
  })().catch((err) => {
    next(new PhoenixError(err));
  });
}
module.exports = {
  requireTestCaseGroupExist,
};
